package fi.roose.uidesignia.ui;


import fi.roose.uidesignia.R;
import fi.roose.uidesignia.data.DataModel;
import fi.roose.uidesignia.data.Restaurant;
import fi.roose.uidesignia.data.Suggestion;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class Design1 extends Activity {
	private static final String TAG = "Design1";

	private static final int LOGON_REQUEST = 42;
	
	private Button mSuggest;
	private ImageButton mLogon;
	private ImageButton mRefresh;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == LOGON_REQUEST && resultCode == RESULT_OK){
			refresh();
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.design1);
	    
	    
	    
	    mSuggest = (Button) findViewById(R.id.design1_btn_suggest);
	    mSuggest.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				handleSuggestButton();
			}
		});
	    
	    mLogon = (ImageButton) findViewById(R.id.design1_btn_logon);
	    mLogon.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				handleGroupSwitch();
			}
		});
	    
	    mRefresh = (ImageButton) findViewById(R.id.desing1_btn_refresh);
	    mRefresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				refresh();
			}
		});
	    
	    refresh();
	}
	
	private void launchLogon(){
		Intent i = new Intent(Design1.this, Logon.class);
		startActivityForResult(i, LOGON_REQUEST);
	}

	private void handleGroupSwitch(){
		final String[] groups = DataModel.getGroups();
		final String[] items = new String[groups.length + 1];
		items[0] = "[ Add new ]";
		for(int i = 0; i < groups.length; i++){
			items[i + 1] = groups[i];
		}
		
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setTitle("Choose group");
		b.setSingleChoiceItems(items, -1, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(which == 0){
					launchLogon();
				} else {
					DataModel.setSelectedGroup(items[which]);
					Toast.makeText(Design1.this, "Selected " + items[which], Toast.LENGTH_LONG).show();
					refresh();
				}
				
				dialog.dismiss();
			}
		});
		
		b.show();
		
	}
	
	private void handleSuggestButton(){
		final Restaurant[] restaurants = DataModel.getRestaurantList();
		
		if(restaurants.length == 0){
			launchLogon();
			return;
		}
		
		final String[] items = new String[restaurants.length + 1];
		for(int i = 0; i < restaurants.length; i++){
			items[i + 1] = restaurants[i].name;
		}
		items[0] = "[ Add new ]";
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setTitle("Choose suggestion");
		b.setSingleChoiceItems(items, -1, new OnClickListener() {
			
			@Override
			public void onClick(final DialogInterface itemListDialog, int which) {
				if(which == 0){
					NewRestaurantDialog dlg = new NewRestaurantDialog(Design1.this);
					dlg.setOnDismissListener(new Dialog.OnDismissListener() {
						
						@Override
						public void onDismiss(DialogInterface newRestaurantDialog) {
							NewRestaurantDialog dismissed = (NewRestaurantDialog) newRestaurantDialog;
							if(dismissed.selectedName != null){
								itemListDialog.dismiss();
							}
						}
					});
					dlg.show();

				} else {
					DataModel.addSuggestion(restaurants[which - 1], "");
					refresh();
					itemListDialog.dismiss();
				}
			}
		});
		
		EditText edit = new EditText(this);
		edit.setHint("Optional message");
		b.setView(edit);

		
		b.show();
	}
	
	
	private void refresh(){
		RestaurantAdapter adapter = new RestaurantAdapter();
		ExpandableListView list = (ExpandableListView) findViewById(R.id.design1_lst_suggestions);
		list.setAdapter(adapter);
		Suggestion s = DataModel.getMySuggestion();
		if(s != null){
			mSuggest.setText(s.restaurant.name);
		}
		
	    String title = getResources().getString(R.string.app_name);
	    String group = DataModel.getSelectedGroup();
	    if(group != null) {
	    	title += " - " + group;
	    }
	    setTitle(title);
	}
	

	public class RestaurantAdapter extends BaseExpandableListAdapter {

		final private Suggestion[] suggestions = DataModel.getSuggestions();

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			Log.d(TAG, "getChild");
			return null;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			Log.d(TAG, "getChildId");
			return 0;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			Log.d(TAG, "getChildView");
			convertView = getLayoutInflater().inflate(
					R.layout.design1_expanded_child, parent, false);
			
			final Suggestion suggestion = suggestions[groupPosition];
/*
			TextView message = (TextView) convertView.findViewById(R.id.design1_expanded_child_message);
			TextView score = (TextView) convertView.findViewById(R.id.design1_expanded_child_score);
			LinearLayout group = (LinearLayout) convertView.findViewById(R.id.design1_expanded_child_scoregroup);
			RatingBar bar = (RatingBar) convertView.findViewById(R.id.design1_expanded_child_rating);
			
			message.setText(suggestion.message);
			
			bar.setTag(new VoteRefresher(score, group, suggestion, bar, 2));

*/
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			Log.d(TAG, "getChildrenCount");
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			Log.d(TAG, "getGroup");
			return suggestions[groupPosition];
		}

		@Override
		public int getGroupCount() {
			Log.d(TAG, "getGroupCount " + suggestions.length);
			return suggestions.length;
		}

		@Override
		public long getGroupId(int groupPosition) {
			Log.d(TAG, "getGroupId");
			return 0;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			convertView = getLayoutInflater().inflate(R.layout.design1_non_expanded, parent, false);
			TextView name = (TextView) convertView.findViewById(R.id.design1_nonexpanded_item_name);
			final Suggestion suggestion = suggestions[groupPosition];
			name.setText(suggestion.restaurant.name);
			
			
			
			RatingBar bar = (RatingBar) convertView.findViewById(R.id.design1_ratebar_non_expanded);
			TextView score = (TextView) convertView.findViewById(R.id.design1_nonexpanded_item_score);
			TextView comment = (TextView) convertView.findViewById(R.id.design1_nonexpanded_item_comment);
			LinearLayout group = (LinearLayout) convertView.findViewById(R.id.design1_nonexpanded_item_scoregroup);
			comment.setText(suggestion.message);
			
			bar.setTag(new VoteRefresher(score, group, suggestion, bar, 0));

			return convertView;
		}
		
		
		@Override
		public boolean hasStableIds() {
			Log.d(TAG, "hasStableIds");
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			Log.d(TAG, "isChildSelectable");
			return false;
		}
	}


	
	private class VoteRefresher implements RatingBar.OnRatingBarChangeListener{
		public final TextView score;
		public final LinearLayout group;
		public final Suggestion suggestion;
		private final int iconPos;

		VoteRefresher(TextView score, LinearLayout group, Suggestion suggestion, RatingBar bar, int iconPos){
			this.score = score;
			this.group = group;
			this.suggestion = suggestion;
			this.iconPos = iconPos;
			
			if(bar.isFocusable()){
				bar.setFocusable(false);
			}

			Integer myvote = suggestion.getMyVote();
			if(myvote != null){
				bar.setRating(myvote);
			}
			
			bar.setOnRatingBarChangeListener(this);
			refresh();
		}
		
		public void refresh(){
			
			score.setText(Integer.toString(suggestion.getScore()));
			handleDeclines();
		}
		
		@Override
		public void onRatingChanged(RatingBar ratingBar, float rating,
				boolean fromUser) {
			if(fromUser){
				suggestion.setVote((int) rating);
				refresh();
			}
			
		}
		
		private void handleDeclines(){
			final int declines = Math.min(5, suggestion.getNumberOfDeclines());
			final int icons = countDeclineIcons();
			if(declines < icons){
				int remove = Math.abs(declines - icons);
				while(remove > 0){
					group.removeViewAt(iconPos);
					remove--;
				}
			} else if (declines > icons){
				int add = Math.abs(declines - icons);
				int size = score.getLayoutParams().height;
				ViewGroup.LayoutParams l = new LayoutParams(size, size);
				while (add > 0){
					ImageView im = new ImageView(Design1.this);
					im.setImageResource(R.drawable.ic_banned);
					im.setLayoutParams(l);
					group.addView(im, iconPos);
					add--;
				}
				
			}
			
		}

		private int countDeclineIcons(){
			int count = 0;
			int childs = group.getChildCount();
			for(int i = 0; i < childs; i++){
				View v = group.getChildAt(i);
				if(v instanceof ImageView){
					count++;
				}
			}
			return count;
		}
		
		
	}
	
	private class NewRestaurantDialog extends Dialog{
		
		String selectedName;
		
		public NewRestaurantDialog(Context context) {
			super(context);
			setContentView(R.layout.add_restaurant);
			setTitle("Add new restaurant");
			
			final EditText restaurant = (EditText) findViewById(R.id.add_restaurant_name); 
			final EditText message = (EditText) findViewById(R.id.add_restaurant_msg);
			final Button add = (Button) findViewById(R.id.add_restaurant_ok);
			
			add.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					selectedName = restaurant.getText().toString().trim();
					String msg = message.getText().toString().trim();
					
					
					Restaurant restaurant =  DataModel.addRestaurant(selectedName);
					DataModel.addSuggestion(restaurant, msg);
					dismiss();
					refresh();
				}
			});
			
		}
	
		@Override
		public void onBackPressed() {
			dismiss();
		}
		
	}


}
